<template>
	<view class="material">
		<uni-nav-bar dark :fixed="true" :border="false" background-color="#FFFFFF" status-bar 
			:title="title" left-icon="left" @clickLeft="toBack" color="#000" />
		<scroll-view class="material-body" :scroll-y="true" @scrolltolower="onScroll">
			<view class="material-title">
				<text>{{material.title}}</text>
			</view>
			<view style="height: 40rpx;display: flex;font-size: 25rpx;color: #909399;">
				<view style="display: flex;">
					<!-- <u-icon name="account" size="18"></u-icon> -->
					<text>{{material.nikeName}}</text>
				</view>
				<view style="margin-left: 20rpx;display: flex;">
					<!-- <u-icon name="clock" size="18"></u-icon> -->
					<text>{{formatTimeAgo(material.createTime)}}</text>
				</view>
				<view style="margin-left: 20rpx;display: flex;">
					<u-icon name="eye" size="18"></u-icon>
					<text style="margin-left: 10rpx;">{{material.viewCount}}</text>
				</view>
				<view v-if="learnRecord !== null" style="margin-left: 20rpx;">
					<text v-if="learnRecord.status===0" style="color: #ff9900;">未学习</text>
					<text v-if="learnRecord.status===1" style="color: #5ac725;">已学习</text>
				</view>
			</view>
			<view class="material-content">
				<view v-if="material.isVideo" style="width: 100%;height: 350rpx;">
					<video class="material-content-video"
						:src="READ_VIDEO_URL+material.videoUrl"
						@ended="addViewCount">
					</video>
				</view>
				<view v-html="material.content" style="margin-top: 10rpx;"></view>
			</view>
			<view class="material-comment">
				<view class="material-comment-title">
					<text>全部评论</text>
				</view>
				<view class="material-comment-body">
					<view style="display: flex;margin-bottom: 20rpx;">
						<view style="width: 80rpx;">
							<u-avatar :size="30" :src="READ_IMG_URL+userInfo.image"></u-avatar>
						</view>
						<view style="flex: 1;" @click="inputShow = true">
							<u--input v-model="commentContent" placeholder="发表评论" border="none" 
								readonly :customStyle="inputStyle">
							</u--input>
						</view>
					</view>
					<view class="comment-row" v-for="(item,index) in commentList" :key="index">
						<view style="width: 80rpx;">
							<u-avatar :size="30" :src="READ_IMG_URL+item.image"></u-avatar>
						</view>
						<view style="flex: 1;">
							<view style="width: 100%;color: #606266;;margin: 5rpx 0 5rpx 0;">
								<text>{{item.userName}}</text>
							</view>
							<view style="padding: 10rpx 0;">
								<textarea class="textarea" v-model="item.content" disabled 
									auto-height>
								</textarea>
							</view>
							<view style="font-size: 25rpx;display: flex;justify-content: space-between;color: #909399;">
								<text>{{formatTimeAgo(item.createTime)}}</text>
								<u-icon name="close" size="18" v-if="deleteShow(item)" 
									@click="deleteComment(item)">
								</u-icon>
							</view>
							<view style="height: 10rpx; border-bottom: 1px #e3e5e7 solid;"
								v-if="index !== commentList.length-1">
							</view>
						</view>
					</view>
					<u-loadmore :status="status" line nomore-text="已经到底啦" />
				</view>
			</view>
		</scroll-view>
		<!-- 发布评论 -->
		<u-popup :show="inputShow" @close="closeInput">
		    <view class="popup-body">
		        <u--textarea v-model="commentContent" placeholder="说点什么吧" focus autoHeight 
					:maxlength="-1" :showConfirmBar="false">
				</u--textarea>
				<view style="margin-left: 10rpx;">
					<u-button :plain="true" text="发表" @click="publishComment"></u-button>
				</view>
		    </view>
		</u-popup>
		<view style="width: 100%;height: 20rpx;"></view>
	</view>
</template>

<script>
	import companyApi from "../../request/companyCultureApi.js";
	import config from "../../request/config.js";
	export default {
		data(){
			return {
				READ_IMG_URL: config.READ_IMG_URL,
				READ_VIDEO_URL: config.READ_VIDEO_URL,
				userInfo: {},
				materialId: "",
				material: {},
				title: "",
				learnRecord: null,
				commentList: [],
				formComment: {
					materialId: null,
					currentPage: 1,
					pageSize: 10,
				},
				commentContent: "",
				inputStyle: {
					height: "100%",
					backgroundColor: "#f4f4f5"
				},
				inputShow: false,
				timeOutId: null,
				status: "loadmore",
				notData: false 
			}
		},
		onLoad(params) {
			this.userInfo=uni.getStorageSync("loginUser");
			this.materialId = params.id
			if (this.materialId){
				this.getMaterial();
				this.getComment();
			}
		},
		destroyed() {
			clearTimeout(this.timeOutId);
		},
		methods: {
			// 返回上个页面
			toBack() {
				uni.navigateBack({
					delta: 1, // 返回的页面数，1表示返回上一页
					animationType: 'pop-out', // 页面关闭的动画效果
					animationDuration: 300, // 页面关闭的动画时间
				});
			},
			// 获取详情
			getMaterial(){
				const data = {
					id: this.materialId
				}
				companyApi.getMaterial(data).then(res =>{
					if (res.code === 200){
						this.material = res.data;
						if (this.material.type === 0){
							this.title="学习资料"
							this.getLearnRecord();
						}else if (this.material.type === 1){
							this.title="培训视频"
							this.getLearnRecord();
						}else if (this.material.type === 2){
							this.title="会议视频"
						}else if (this.material.type === 3){
							this.title="公司文化"
						}else if (this.material.type === 4){
							this.title="管理制度"
						}
						if (this.material.videoUrl!== null && this.material.videoUrl!==''){
							this.material.isVideo = true
						}else {
							this.material.isVideo = false
							// 没有视频，使用计时一分钟来算浏览量和学习状态
							this.timeOutId = setTimeout(() => {
							    this.addViewCount();
							}, 60000)
						}
					}
				})
			},
			// 获取学习记录
			getLearnRecord(){
				const data = {
					materialId: this.materialId
				}
				companyApi.getLearnRecord(data).then(res =>{
					if (res.code === 200){
						this.learnRecord = res.data
					}
				})
			},
			// 改变学习状态
			changeStatus(){
				if (this.learnRecord.status === 0){
					companyApi.changeStatus(this.learnRecord).then(res =>{
						if (res.code === 200){
							this.learnRecord.status = 1;
							this.$tip.tip("已完成学习");
						}
					})
				}
			},
			// 获取评论
			getComment(){
				this.formComment.materialId = this.materialId;
				companyApi.getComment(this.formComment).then(res =>{
					if (res.code === 200){
						if (res.data.length === 0){
							this.notData = true;
							this.status = "nomore";
						}else {
							res.data.forEach(item =>{
								item.im
								this.commentList.push(item);
							})
							if (res.data.length < this.formComment.pageSize){
								this.status = "nomore";
							}
						}
					}
				})
			},
			// 发布评论
			publishComment(){
				if (this.commentContent === "") {
					this.$tip.tip("不能发表空评论！");
					return;
				}
				const data ={
					content:this.commentContent,
					materialId:this.material.id
				}
				companyApi.addComment(data).then(res =>{
					if (res.code === 200){
						this.$tip.tip(res.message)
						this.commentList.unshift(res.data)
						this.commentContent = "";
						this.closeInput();
					}
				})
			},
			// 关闭发表评论
			closeInput(){
				this.inputShow = false;
			},
			// 删除是否显示
			deleteShow(item){
				return item.userId === this.userInfo.id;
			},
			// 删除评论
			deleteComment(item){
				let _this = this
				uni.showModal({
					title: '提示',
					content: '确定要删除该评论吗？',
					success: function(res) {
						if (res.confirm) {
							console.log('用户点击确定');
							companyApi.deleteUserComment(item).then(res =>{
								if (res.code === 200){
									// 从数组中删除
									const index = _this.commentList.findIndex(comment => 
										comment.id === item.id);
									_this.commentList.splice(index, 1);
									_this.$tip.tip("删除成功");
								}
							})
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}
				});
			},
			// 增加浏览量，完成学习
			addViewCount(){
				console.log("浏览量加1")
				// 先给视频加浏览量
				const data = {
					id: this.material.id
				}
				companyApi.addViewCount(data).then(res =>{
					if (res.code === 200){
						
					}
				})
				// 给学习资料和培训视频设置已学习状态
				if (this.material.type === 0 || this.material.type === 1){
					this.changeStatus();
				}
			},
			// 计算时间差
			formatTimeAgo(time){
				const now = new Date();
				const target = new Date(time);
				// 计算时间差（单位：毫秒）
				const diff = now.getTime() - target.getTime();
				// 小于1分钟，返回xx秒前
				if (diff < 60000) {
					const seconds = Math.floor(diff / 1000);
					return `${seconds}秒前`;
				}
				// 小于1小时，返回xx分钟前
				if (diff < 3600000) {
					const minutes = Math.floor(diff / 60000);
					return `${minutes}分钟前`;
				}
				// 小于1天，返回xx小时前
				if (diff < 86400000) {
					const hours = Math.floor(diff / 3600000);
					return `${hours}小时前`;
				}
				// 大于等于1天，直接返回该时间
				return time;
			},
			// 滑到评论底部
			onScroll(){
				if (!this.notData){
					this.formComment.currentPage++;
					this.getComment();
				}
			}
		}
	}
</script>

<style>
	.material{
		width: 100%;
		min-height: 100vh;
	}
	
	.material-body{
		width: 94%;
		height: 88vh;
		margin: auto;
	}
	
	.material-title{
		font-size: 40rpx;
		font-weight: bold;
		margin: 20rpx 0;
	}
	
	.material-content-video{
		width: 100%;
		height: 100%;
	}
	
	.material-comment{
		
	}
	
	.material-comment-title{
		font-size: 30rpx;
		font-weight: bold;
		margin: 20rpx 0;
	}
	
	.comment-row{
		display: flex;
	}
	
	.popup-body{
		display: flex;
		min-height: 80rpx;
		padding: 20rpx;
		
	}
</style>